package org.kermeta.spem.activityautomation.eclipse.shareprojectsvn;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.kermeta.spem.activityautomationmanager.ActivityAutomation;
import org.kermeta.spem.executioncontext.ExecutionContext;
import org.kermeta.spem.processexecution.utils.model.ModelUtils;
import org.kermeta.spem.versioncontrolsystem.SVNClient;

public class ShareProjectSVNActivityAutomation implements ActivityAutomation {

	public ShareProjectSVNActivityAutomation() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run(String contextModelPath) {
		
		//Get the execution context
		ExecutionContext executionContext = ModelUtils.getExecutionContextRoot(contextModelPath);
		
		//Get the name of the project to put under version control
		String projectName = ModelUtils.getValueOfKey("name of the newly created project",executionContext);
		
		//Get the URL of the SVN repository
		String svnRepositoryURL = ModelUtils.getValueOfKey("url of the remote repository", executionContext);

		SVNClient svnClient = new SVNClient();

		//Create a new directory on the svn repository
		svnClient.createDirectory(svnRepositoryURL+"/"+projectName, "");

		//Checkout this directory
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		svnClient.checkoutDirectory(svnRepositoryURL+"/"+projectName, new File(workspace.getRoot().getLocation().toString()+"/"+projectName));

		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);

		//Add the project's resources to version control, except for the bin directory
		IResource[] members;
		try {
			members = project.members();

			for (IResource res : members) {
				if (res instanceof IFolder) {
					IFolder folder = (IFolder) res;
					if (!folder.getName().equals("bin")) {
						svnClient.addDirectory(folder.getLocation().toFile(), true);
					}
				} else if (res instanceof IFile) {
					File file = ((IFile) res).getLocation().toFile();
					svnClient.addFile(file);
				}
			}
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Ignore the bin directory
		svnClient.addToIgnoredPatterns(project.getLocation().toFile(), "bin");

		//Refresh the project that has been put under version control
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

}
